package com.bds.portal.service;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.codehaus.plexus.util.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.SendResult;
import com.bds.model.Result;
import com.bds.model.Task;
import com.bds.model.Template;
import com.bds.model.TemplateUrl;
import com.bds.portal.queue.TcpUrlProducer;
import com.bds.portal.util.Const;
import com.bds.portal.util.HTMLUploadOSSUtil;

@Component
public class PortalService {
	private static Logger logger = Logger.getLogger(PortalService.class);

	@Resource
	private NutDao portalDao;
	@Resource
	private MyTUrlService myTUrlService;

	public Result addTask(String requestId, String url, String uuid, String prid) {
		Result ret = new Result();
		try {
			java.net.URL u = new java.net.URL(url);
			String host = u.getHost();// 获取主机名
			final Task task = new Task();
			task.setCreate_time(new Date());
			task.setUuid(uuid);
			task.setHost(host);
			task.setUrl(url);
			task.setPrid(prid);
			task.setRequestId(requestId);
			task.setStatus(0);
			portalDao.fastInsert(task);
//			JSONObject msg = new JSONObject();
//			msg.put("url", url);
//			msg.put("id", task.getId());
//			msg.put("requestId", requestId);
//			msg.put("userId", task.getUserId());
//			msg.put("table", "t_task");
//			msg.put("isjs", "0");
//			SendResult send = TcpUrlProducer.getInstance().send(msg.toJSONString(), "protal");
//
//			if (send != null && send.getMessageId() != null) {
			//	portalDao.update(Task.class, Chain.make("status", 1), Cnd.where("id", "=", task.getId()));
				ret.setResult(Const.SUC, task);
//			} else {
//				portalDao.update(Task.class, Chain.make("status", 3), Cnd.where("id", "=", task.getId()));
//				ret.setResult(Const.FAIL_400, "发送失败");
//			}
		} catch (Exception e) {
			ret.setResult(Const.FAIL_400, "服务器异常");
			logger.error("", e);
		}
		return ret;
	}

	public Result getHtml(String requestId, String isjs) {
		Result ret = new Result();
		try {
			String html = HTMLUploadOSSUtil.downloadHtml(requestId);
			if (StringUtils.isNotEmpty(html)) {
				Document doc = Jsoup.parse(html);

				// 移除js
				if (!StringUtils.isEmpty(isjs)) {
					if (isjs.equals("0")) {
						Elements ejs = doc.select("script");
						for (int i = 0; i < ejs.size(); i++) {
							Element e = ejs.get(i);
							if (e.attributes().hasKey("src")) {
								String src = e.attr("src");
								if (StringUtils.isNotEmpty(src)) {
									if (src.indexOf("think-data.cn") < 0 && src.indexOf("localhost") < 0) {
										e.remove();
									}
								}
							}
						}
					}
				} else {
					Elements ejs = doc.select("script");
					for (int i = 0; i < ejs.size(); i++) {
						Element e = ejs.get(i);
						if (e.attributes().hasKey("src")) {
							String src = e.attr("src");
							if (StringUtils.isNotEmpty(src)) {
								if (src.indexOf("think-data.cn") < 0 && src.indexOf("localhost") < 0) {
									e.remove();
								}
							}
						}
					}
				}

				// Elements elements = doc.getAllElements();
				// for (int i = 0; i < elements.size(); i++) {
				// Element e = elements.get(i);
				// if (e.tagName().equals("a")) {
				// String h = e.attr("href");
				// if (StringUtils.isNotEmpty(h)) {
				// if (h.indexOf("javascript") < 0) {
				// e.attributes().remove("href");
				// }
				// }
				// }
				// }

				// 返回前端时，去除a标签中的href

				html = doc.html();
			}

			ret.setCode(Const.SUC);
			ret.setData(html);
		} catch (Exception e) {
			ret.setResult(Const.FAIL_500, "获取html异常");
		}
		return ret;
	}

	public Template getTemplate(String requestId) {

		Template t = portalDao.fetch(Template.class, Cnd.where("request_id", "=", requestId));
		List<TemplateUrl> tp = myTUrlService.getAllTUrl(requestId);
		StringBuffer buf = new StringBuffer();
		for (TemplateUrl u : tp) {
			buf.append(u.getUrl() + "\n");
		}
		if (buf.length() > 0) {
			buf = buf.deleteCharAt(buf.length() - 1);
			t.setUrls(buf.toString());
		}

		return t;
	}

	public void upEmail(String email) {

		try {
			if (StringUtils.isNotEmpty(email)) {
				email = java.net.URLDecoder.decode(email);
				portalDao.update("t_mail", Chain.make("status", 2), Cnd.where("email", "=", email));
			}

		} catch (Exception e) {

			logger.error("", e);
		}

	}

	public Task getTask(String requestId) {

		try {
			Task task = portalDao.fetch(Task.class, Cnd.where("request_id", "=", requestId));

			return task;
		} catch (Exception e) {

			logger.error("", e);
		}
		return null;
	}

	public String getTaskUrl(String requestId) {
		String ret = "";
		try {
			String url = portalDao.fetch(Task.class, Cnd.where("request_id", "=", requestId)).getUrl();
			return url;
		} catch (Exception e) {
			logger.error("", e);
		}
		return ret;
	}
}
